﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Dynamic;
using System.ComponentModel;
using CCH.Entity;

namespace CCH.DAO
{
    [DataObject(true)]
    public class albumDAO
    {
        private Entities model = new Entities();

        public IQueryable<Photoalbum> Get_album_AllData(int alb_type)
        {
            var data = from d in model.album
                       join p in model.photo on new { ID = d.alb_no, photo = d.alb_cover.Value } equals new { ID = p.alb_no, photo = p.pho_no } into k
                       from p2 in k.DefaultIfEmpty()
                       where d.state == "1" && d.alb_type == alb_type
                       orderby d.createtime descending
                       select new Photoalbum { Album = d, Cover = p2, Count = (from p3 in model.photo where p3.alb_no == d.alb_no select d).Count() };

            return data;
        }

        public album Get_album(int alb_no)
        {
            return (from d in model.album where d.alb_no == alb_no select d).FirstOrDefault();
        }

        public void Add_album(album d)
        {
            model.album.AddObject(d);
            Update();
        }

        public void Delete_album(int alb_no, int peo_uid)
        {
            album d = Get_album(alb_no);
            d.state = "2";
            d.createuid = peo_uid;
            d.createtime = DateTime.Now;
            Update();
        }

        /// <summary>
        /// 取回相片
        /// </summary>
        /// <param name="alb_no"></param>
        /// <returns></returns>
        public IQueryable<photo> Get_photo_AllData(int alb_no)
        {
            return from d in model.photo where d.alb_no == alb_no orderby d.pho_createtime descending select d;
        }

        public photo Get_photo(int alb_no, int pho_no)
        {
            return (from d in model.photo where d.alb_no == alb_no && d.pho_no == pho_no select d).FirstOrDefault();
        }

        public int Get_photo_Count(int alb_no)
        {
            var data = (from d in model.photo where d.alb_no == alb_no select d.pho_no);

            if (data.Count() > 0)
            {
                return data.Max();
            }
            else
            {
                return 0;
            }
        }

        public int Get_photo_Check(string filepath)
        {
            return (from d in model.photo where d.pho_file == filepath select d).Count();
        }

        public void Add_photo(photo d)
        {
            model.photo.AddObject(d);
            Update();
        }

        public void Delete_photo(int alb_no, int pho_no)
        {
            photo d = Get_photo(alb_no, pho_no);
            model.photo.DeleteObject(d);
        }


        public void Update()
        {
            model.SaveChanges();
        }
    }
}
